package com.alogic.event.xscript;

import com.alogic.event.Event;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 获取当前事件的属性
 *
 * @since 1.6.12.38 [20190715] <br>
 */
public class ListProperty extends Segment {
    protected String pid = "$event-read";
    protected String $key = "$key";
    protected String $value = "$value";

    public ListProperty(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        $key = PropertiesConstants.getRaw(p,"key",$key);
        $value = PropertiesConstants.getRaw(p,"value",$value);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        Event e = ctx.getObject(pid);
        if (e != null){
            String [] keys = e.getKeys();
            for (String key:keys){
                String value = e.getProperty(key,"");
                if (StringUtils.isNotEmpty(value)){
                    ctx.SetValue(PropertiesConstants.transform(ctx,$key,"$key"),key);
                    ctx.SetValue(PropertiesConstants.transform(ctx,$value,"$value"),value);
                    super.onExecute(root,current,ctx,watcher);
                }
            }
        }
    }
}